package com.netty.model;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;

public class LogonPacket extends Packet {
	public String userName;
	public String password;
	
	public byte[] serialize() {
		// userName = "william"
		// password = "123456"
		int totalLength = 12 + userName.length() + password.length();
		
		byte[] buffer = new byte[totalLength];
		
		int offset = 0;
		
		// copy totalLength to buffer
		byte[] totalLengthBuffer = Util.int2bytes(totalLength);
		System.arraycopy(totalLengthBuffer, 0, buffer, offset, 4);
		offset += 4;
		
		// copy packet type to buffer
		byte[] packetTypeBuffer = Util.int2bytes(Service.PACKET_TYPE.C2S_LOGON);
		System.arraycopy(packetTypeBuffer, 0, buffer, offset, 4);
		offset += 4;
		
		// copy user name length to buffer
		byte[] userNameLengthBuffer = Util.int2bytes(userName.length());
		System.arraycopy(userNameLengthBuffer, 0, buffer, offset, 4);
		offset += 4;
		
		// copy user name to buffer
		System.arraycopy(userName.getBytes(), 0, buffer, offset, userName.length());
		offset += userName.length();
		
		// copy password to buffer
		System.arraycopy(password.getBytes(), 0, buffer, offset, password.length());
		offset += password.length();
		
		return buffer;
	}

	public void unserialize(byte[] data) {
		// decode total length
		int totalLength = Util.bytes2int(data, 0);
		
		// decode user name length
		int userNameLength = Util.bytes2int(data, 8);
		
		userName = new String(data, 12, userNameLength);
		
		password = new String(data, 12 + userNameLength, totalLength - 12 - userNameLength);
	}
}
